package io.github.junxworks.qt.modules.bi.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import io.github.junxworks.ep.core.Result;
import io.github.junxworks.ep.sys.service.EpDataService;
import io.github.junxworks.qt.modules.bi.service.MainService;
import io.github.junxworks.qt.modules.bi.vo.Series;
import io.github.junxworks.qt.modules.bi.vo.TradeDateStat;

@RestController
@RequestMapping("/bi/main")
public class MainController {
	@Autowired
	private MainService mainService;

	@Autowired
	private EpDataService dataService;

	@GetMapping("/changes-daily")
	public Result changeStatDaily(@RequestParam("market") String market, @RequestParam("days") int days) {
		Result res = Result.ok();
		List<TradeDateStat> tds = mainService.statChangeDaily(days, market);
		List<String> legendData = Lists.newArrayList("上涨", "涨停", "下跌", "跌停");
		List<String> xAxisData = Lists.newArrayList();
		Series up = new Series();
		up.setName("上涨");
		up.setStack("1");
		up.setType("bar");
		Series down = new Series();
		down.setName("下跌");
		down.setStack("1");
		down.setType("bar");
		Series upp = new Series();
		upp.setName("涨停");
		upp.setStack("1");
		upp.setType("bar");
		Series dp = new Series();
		dp.setName("跌停");
		dp.setStack("1");
		dp.setType("bar");
		List<Series> series = Lists.newArrayList(up, upp, down, dp);
		tds.stream().forEach(v -> {
			String date = v.getTradeDate();
			xAxisData.add(date);
			up.addData(v.getUpCount());
			upp.addData(v.getUppCount());
			down.addData(v.getDownCount());
			dp.addData(v.getDownpCount());
		});
		res.addAttribute("legendData", legendData);
		res.addAttribute("xAxisData", xAxisData);
		res.addAttribute("series", series);
		return res;
	}

	@GetMapping("/ranks/{sqlId}")
	public Result changeStatDaily(@PathVariable("sqlId") String sqlId, @RequestParam Map<String, String> params) throws Exception {
		Result res = Result.ok();
		List<Map<String, Object>> tds = dataService.getDataBySQLUid(sqlId, params);
		tds = Lists.reverse(tds);
		List<String> categories = Lists.newArrayList();
		Series series = new Series();
		series.setType("bar");
		tds.forEach(m -> {
			categories.add(String.valueOf(m.get("category")));
			series.addData(m.get("s_data"));
			series.addLable("show", true);
			series.addLable("position", params.getOrDefault("label_position", "right"));
		});
		res.addAttribute("categories", categories);
		res.addAttribute("series", Lists.newArrayList(series));
		return res;
	}
}
